package com.thinkgem.jeesite.modules.sys.web;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.product.entity.attribute.TbProductAttribute;
import com.thinkgem.jeesite.modules.product.entity.dict.TbProductAttributeDict;
import com.thinkgem.jeesite.modules.product.service.attribute.TbProductAttributeService;
import com.thinkgem.jeesite.modules.product.service.dict.TbProductAttributeDictService;
import com.thinkgem.jeesite.modules.sys.dao.TbAttachmentMapper;
import com.thinkgem.jeesite.modules.sys.entity.*;
import com.thinkgem.jeesite.modules.sys.service.ProductService;
import com.thinkgem.jeesite.modules.sys.service.TbAgentProductService;
import com.thinkgem.jeesite.modules.sys.service.TbShopProductService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * Created by jyy on 2016/10/21 0021.
 */


@Controller
@RequestMapping(value = "${adminPath}/sys/product")
public class TbProductController extends BaseController {

    @Autowired
    private ProductService productService;
    @Autowired
    private TbAgentProductService tbAgentProductService;
    @Autowired
    private TbShopProductService tbShopProductService;

    @Autowired
    private TbProductAttributeService tbProductAttributeService;

    @Autowired
    private TbAttachmentMapper tbAttachmentMapper;

    @Autowired
    private TbProductAttributeDictService productAttributeDictService;


    /**
     * 执行所有方法前先获取tbproduct
     *
     * @param id
     * @return
     */
    @ModelAttribute
    public TbProduct get(@RequestParam(required = false) Integer id) {
        if (null != id) {
            return productService.get(id);
        } else {
            return new TbProduct();
        }
    }


    /**
     * 跳转到编辑商品页面
     *
     * @param tbProduct
     * @param model
     * @return
     */
    @RequestMapping(value = "form")
    public String form(TbProduct tbProduct, Model model,HttpServletResponse response) {
        if (tbProduct.getId() != null && !"".equals(tbProduct.getId())) {
            TbCategory tbCategory = productService.getTbCategory(tbProduct.getCategoryId());
            List<TbAgentProduct> tbAgentProduct = productService.getTbAgentProduct(tbProduct.getId());
            model.addAttribute("tbAgentProduct", tbAgentProduct.get(0));
            model.addAttribute("tbAgentProductList", tbAgentProduct);
            model.addAttribute("category", tbCategory);
            //pics
            List<TbAttachment> tbAttachments = this.tbAttachmentMapper.selectByFkId(tbProduct.getId());
            model.addAttribute("tbAttachments", tbAttachments);
            //attributes
            TbProductAttribute tbProductAttribute = new TbProductAttribute();
            tbProductAttribute.setProductId(tbProduct.getId());
            List<TbProductAttribute> tbProductAttributes = this.tbProductAttributeService.findList(tbProductAttribute);
            Map<String, List<TbProductAttribute>> map = new HashMap<String, List<TbProductAttribute>>();
            if (!tbProductAttributes.isEmpty()) {
                for (TbProductAttribute attribute : tbProductAttributes) {
                    TbProductAttributeDict dict = new TbProductAttributeDict();
                    dict.setCode("TYPE");
                    dict.setValue(attribute.getProductAttr());
                    List<TbProductAttributeDict> list1 = this.productAttributeDictService.findList(dict);
                    if (list1.size() == 0) {
                        continue;
                    }
                    List<TbProductAttribute> list = map.get(list1.get(0).getOption());
                    if (list == null) {
                        list = new ArrayList<TbProductAttribute>();
                    }
                    list.add(attribute);
                    map.put(list1.get(0).getOption(), list);
                }
            }
            model.addAttribute("map", map);
        }
        tbProduct = this.productService.get(tbProduct.getId());
        if(tbProduct.getId()!=null){
            model.addAttribute("tbProduct", tbProduct);
            model.addAttribute("flag", 1);
            model.addAttribute("listLength", tbProduct.getTbAgentProduct().size());
        }else{
            TbProduct product = new TbProduct();
            model.addAttribute("tbProduct", product);
            model.addAttribute("flag", 0);
        }
        TbProductAttributeDict dict = new TbProductAttributeDict();
        dict.setCode("type");
        List<TbProductAttributeDict> productAttributeDicts = productAttributeDictService.findList(dict);
        model.addAttribute("attribute", productAttributeDicts);
        return "modules/sys/showProductForm";
    }

    /**
     * 查询所有商品——分页
     *
     * @param tbProduct
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(value = {"showProductList", ""})
    public String showProductList(TbProduct tbProduct, HttpServletRequest request, HttpServletResponse response, Model model) {
        User user = UserUtils.getUser();
        tbProduct.setAgentId(user.getId());
        Page<TbProduct> page = productService.findProductByPage(new Page<TbProduct>(request, response), tbProduct);
        model.addAttribute("page", page);
        if(page.getList().size()==0){
            model.addAttribute("message1","无查询结果");
        }
        return "modules/sys/showProductList";

    }
    /**
     * 增加或更改商品
     * @param tbProduct
     * @param model
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "productEdit")
    public String productEdit(TbProduct tbProduct, Model model, RedirectAttributes redirectAttributes,
                              HttpServletRequest request) {
        User currentUser = UserUtils.getUser();
        if (StringUtils.isNotBlank(tbProduct.getTitle())) {
            tbProduct.setProductDesc(StringEscapeUtils.unescapeHtml4(tbProduct.getProductDesc()));
            int id = productService.saveOrUpdateProduct(tbProduct);
            if (tbProduct.getUploadUrl() != null && tbProduct.getUploadUrl().size() > 0) {
                productService.insertProductImg(id, tbProduct.getUploadUrl());
            }
            model.addAttribute("message", "保存商品信息成功");
        }
        model.addAttribute("message","编辑商品成功");
        return "redirect:showProductList";
    }
    //预定商品簽約storageOut
    @RequestMapping(value = "storage")
    public String photoUpload(HttpServletRequest request,Model model) {
        String productId = request.getParameter("id");
        String reserveFlag=request.getParameter("reserveFlag");
        //代理商商品表id 查询是否在店铺有这个商品
        TbAgentProduct agentProduct = tbAgentProductService.selectById(productId);
        TbShopProduct tbShopProduct = tbShopProductService.selectProByProId(agentProduct.getProductId(),agentProduct.getAttr());
        if(tbShopProduct!=null&&tbShopProduct.getId()!=null){
            model.addAttribute("message", "该商品已经签约！");
            return "forward:" + adminPath + "/sys/tbShopController/showAgentProduct/"+reserveFlag+"?repage";
        }else{
            tbShopProductService.insertProWithAgentPro(productId);
            model.addAttribute("message", "商品签约成功！");
            return "forward:" + adminPath + "/sys/tbShopController/showAgentProduct/"+reserveFlag+"?repage";
        }
    }
    //预定商品簽約storageOut
    @RequestMapping(value = "storageOut")
    public String storageOut(HttpServletRequest request,Model model,RedirectAttributes redirectAttributes) {
        String productId = request.getParameter("id");
        String reserveFlag=request.getParameter("reserveFlag");
        String attr = request.getParameter("attr");
        if(StringUtils.isEmpty(productId)){
            addMessage(redirectAttributes, "商品解约失败");
            return "forward:" + adminPath + "/sys/tbShopController/showAgentProduct/"+reserveFlag+"?repage";
        }else{
            //代理商商品表id 查询是否在店铺有这个商品
            Integer id= Integer.parseInt(productId);
            TbAgentProduct agentProduct = tbAgentProductService.selectById(productId);
            TbShopProduct tbShopProduct = tbShopProductService.selectProByProId(agentProduct.getProductId(),agentProduct.getAttr());
            if(tbShopProduct!=null&& tbShopProduct.getStatus()==1){
               model.addAttribute("message1", "上架商品不允许解约！");
               // addMessage(redirectAttributes, "上架商品不允许解约！");
            }else {
                int count = tbShopProductService.deleteProWithAgentPro(tbShopProduct);
                if(count>0){
                    addMessage(redirectAttributes, "商品解约成功");
                }else{
                    addMessage(redirectAttributes, "商品解约失败");
                }
            }
        }

        return "forward:" + adminPath + "/sys/tbShopController/showAgentProduct/"+reserveFlag+"?repage";
    }
    @RequestMapping(value = "delete")
    public String delete(TbProduct tbProduct, RedirectAttributes redirectAttributes) {
        if (Global.isDemoMode()) {
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:" + adminPath + "/sys/product/showProductList/?repage";
        }
        TbAgentProduct tbAgentProduct = tbAgentProductService.selectByProductId(tbProduct.getId());
        if(tbAgentProduct!=null&&"1".equals(tbAgentProduct.getStatus())){
            addMessage(redirectAttributes, "上架商品不允许删除！");
        }else {
            productService.delete(tbProduct);
            addMessage(redirectAttributes, "删除商品成功");
        }
            return "redirect:" + adminPath + "/sys/product/showProductList/?repage";
    }
    @RequestMapping("/checkBarcode")
    public void checkBarcode(HttpServletRequest request, HttpServletResponse response,String barcode,String reverflag) {
        response.setContentType("text/html;charset=UTF-8");
        //根据reverflag，查询该商品所属类别
        //根据条形码和是否是预定决定该商品为哪种商品
        TbProduct tbProduct = productService.selectProductBybarcode(barcode,reverflag);
        try {
            if (tbProduct != null) {
                response.getWriter().print(tbProduct.getId());
            } else {
                response.getWriter().print("0");
            }
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载导入商品数据模板
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "import/templateProduct")
    public String importFileTemplateTenement(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "商品信息导入模板.xlsx";
            List<TbProductImport> list = Lists.newArrayList(); /*list.add(UserUtils.getUser());*/
            new ExportExcel("商品信息", TbProductImport.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
        }
        return "redirect:showProductList";
    }
    /**
     * 导入物业费数据
     * @param file
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "importProduct", method= RequestMethod.POST)
    public String importTenementFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
        if(Global.isDemoMode()){
            addMessage(redirectAttributes, "演示模式，不允许操作！");
            return "redirect:showProductList";
        }
        try {
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<TbProductImport> list = ei.getDataListforProduct(TbProductImport.class);
            if(list.size()>0){
                String msg=productService.importProduct(list);
                addMessage(redirectAttributes,msg);

            }else{
                addMessage(redirectAttributes, "导入商品信息失败！商品信息不能为空");
            };
        } catch (Exception e) {
            addMessage(redirectAttributes, "导入商品信息失败！失败信息："+e.getMessage());
        }
        return "redirect:showProductList";
    }
}
